import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/util/tools.dart';

class ShopCart extends ChangeNotifier {
  var carts = <GoodInfo>[];
  var allSelect = false;
  var total = 0;
  var isShow = false;

  ShopCart._instance();
  static final _shopCart = ShopCart._instance();
  factory ShopCart() => _shopCart;

  Future getCarts() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    final getJson = prefs.getString('carts');
    if (getJson != null) {
      carts = ShopCart.fromJson(jsonDecode(getJson)).carts;
    }

    updateValue();
  }

  void saveCarts() {
    final setJson = toJson();
    Shared.setSPValue('carts', jsonEncode(setJson));
  }

  void addGood(GoodInfo goodInfo) {
    carts.add(goodInfo);

    refreshView();
  }

  void refreshView() {
    updateValue();
    saveCarts();
  }

  void updateValue() {
    var value = 0;
    for (var element in carts) {
      if (element.checked) {
        value += (element.goodsPrice * element.count);
      }
    }

    total = value;

    if (carts.isNotEmpty) {
      isShow = true;
      allSelect = carts.every(
        (element) {
          return element.checked;
        },
      );
    } else {
      isShow = false;
      allSelect = false;
    }

    notifyListeners();
  }

  ShopCart.fromJson(Map<String, dynamic> json) {
    if (json['carts'] != null) {
      json['carts'].forEach((v) {
        carts.add(GoodInfo.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['carts'] = carts.map((v) => v.toJson()).toList();
    return data;
  }
}

class GoodInfo {
  var count = 0;
  var checked = true;
  var goodsId = 0;
  var goodsName = '';
  var goodsPrice = 0;
  var goodsSmallLogo = '';

  GoodInfo();

  GoodInfo.fromJson(Map<String, dynamic> json) {
    count = json['count'];
    checked = json['checked'];
    goodsId = json['goodsId'];
    goodsName = json['goodsName'];
    goodsPrice = json['goodsPrice'];
    goodsSmallLogo = json['goodsSmallLogo'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['count'] = count;
    data['checked'] = checked;
    data['goodsId'] = goodsId;
    data['goodsName'] = goodsName;
    data['goodsPrice'] = goodsPrice;
    data['goodsSmallLogo'] = goodsSmallLogo;
    return data;
  }
}
